<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="dramaVo.title" placeholder="Title" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-select v-model="dramaVo.category" placeholder="类目" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in $enum.CATEGORY" :key="'FILTERCATEGORY='+item.value" :label="item.desc"
                   :value="item.value"/>
      </el-select>
      <el-select v-model="dramaVo.area" placeholder="地区" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in $enum.AREA" :key="'FILTERAREA='+item.value" :label="item.desc" :value="item.value"/>

      </el-select>
<!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
<!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key"/>-->
<!--      </el-select>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                 @click="handleDownload">
        导出
      </el-button>
<!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
<!--        reviewer-->
<!--      </el-checkbox>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="dramaList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                       :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
          <el-tag>{{ row.othTitle }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="地区" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.area }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span style="color:red;">{{ row.reviewer }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="Imp" width="80px">-->
      <!--        <template slot-scope="{row}">-->
      <!--&lt;!&ndash;          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />&ndash;&gt;-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="类目" align="center" width="95">
        <template slot-scope="{row}">
          <span>{{ row.category | categoryFilter }}</span>
          <!--          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>-->
          <!--          <span v-else>0</span>-->
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag>
            {{ row.status | dramaStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :sortable="true" label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ new Date(row.createTime) | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
<!--          <el-button v-if="row.status!='published'" size="mini" type="success"-->
<!--                     @click="handleModifyStatus(row,'published')">-->
<!--            Publish-->
<!--          </el-button>-->
<!--          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">-->
<!--            Draft-->
<!--          </el-button>-->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="dramaVo.currentPage" :limit.sync="dramaVo.pageSize"
                @pagination="getDramaList"/>

    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="5vh">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px"
               style="width: 100%; margin: auto;">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title"/>
        </el-form-item>
        <el-form-item label="别名" prop="othTitle">
          <el-input v-model="temp.othTitle"/>
        </el-form-item>
        <el-form-item label="类目" prop="category">
          <el-select v-model="temp.category" class="filter-item" placeholder="请选择类目">
            <el-option v-for="item in $enum.CATEGORY" :key="'CATEGORY='+item.value" :label="item.desc"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in $enum.DramaStatus" :key="'DramaStatus='+item.value" :label="item.desc"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="地区">
          <el-select v-model="temp.area" placeholder="地区" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in $enum.AREA" :key="'AREA='+item.value" :label="item.desc" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开播时间" prop="publishTime">
          <el-date-picker v-model="temp.publishTime" type="datetime" placeholder="Please pick a date"/>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload class="cover-uploader"
                     :action="baseUrl+`/upload/img`"
                     :show-file-list="true"
                     accept="image/*"
                     :on-success="handleUploadCoverSuccess"
                     :before-upload="beforeCoverUpload">
            <el-image v-if="temp.cover" :src="temp.cover | filterImg" fit="cover" alt=""
                      class="cover"></el-image>
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <!--        <el-form-item label="Imp">-->
        <!--          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3"-->
        <!--                   style="margin-top:8px;"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="简介" prop="description">
          <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" v-model="temp.description"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, fetchPv, createArticle, updateArticle} from '@/api/article'
import waves from '@/directive/waves' // waves directive
import {parseTime} from '@/utils'
import Pagination from '@/components/Pagination'
import {deleteDrama, dramaList, queryOne, saveDrama, updateDrama} from '@/api/drama'
import {DramaStatus} from "@/common/constant/module/drama-state";
import {CATEGORY} from "@/common/constant/module/category"; // secondary package based on el-pagination

const calendarTypeOptions = [
  {key: 'CN', display_name: 'China'},
  {key: 'US', display_name: 'USA'},
  {key: 'JP', display_name: 'Japan'},
  {key: 'EU', display_name: 'Eurozone'}
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: {Pagination},
  directives: {waves},
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      dramaList: [],
      dramaVo: {
        title: undefined,
        category: undefined,
        area: undefined,
        currentPage: 1,
        pageSize: 10
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        publishTime: new Date(),
        title: '',
        type: '',
        status: 'published',
        description: '',
        cover: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{required: true, message: 'type is required', trigger: 'change'}],
        timestamp: [{type: 'date', required: true, message: 'timestamp is required', trigger: 'change'}],
        title: [{required: true, message: '标题不能为空', trigger: 'blur'}]
      },
      downloadLoading: false
    }
  },
  created() {
    // var newVar = context => context.keys().map(context);
    // console.log(newVar({a:'1',b:'2'}))
    // this.getList()
    this.getDramaList()
  },
  methods: {
    getDramaList() {
      dramaList(this.dramaVo).then(response => {
        this.dramaList = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.dramaVo.currentPage = 1
      this.getDramaList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {prop, order} = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        title: '',
        status: '',
        type: '',
        cover: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveDrama(this.temp).then((response) => {
            if (response.data.code == 20000) {
              this.dramaList.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateDrama(tempData).then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getDramaList()
          })
        }
      })
    },
    handleDelete(row, index) {
      deleteDrama(row.id).then(response =>{
        if(response.data.code === 20000){
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          this.getDramaList()
        }
      })

    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序列', '标题', '封面', '简介', '类目', '地区', '状态', '开播时间']
        const filterVal = ['id', 'title', 'cover', 'description', 'category', 'area', 'status', 'publishTime']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '剧目列表',
          autoWidth: false
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.dramaList.map(v => filterVal.map(j => {
        if (j === 'publishTime') {
          return parseTime(new Date(v[j]))
        } else if (j === 'category') {
          return this.$enum.getDescByValue('CATEGORY', v[j])
        } else if (j === 'status') {
          return this.$enum.getDescByValue('DramaStatus', v[j])
        } else if (j === 'cover') {
          return this.$getImg(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    //图片上传成功回调钩子
    handleUploadCoverSuccess(res, file, fileList) {
      let data = res.data
      if (data.path) {
        this.temp.cover = data.path
      }
    },
    //图片上传失败回调钩子
    beforeCoverUpload(file) {

    },
    validateTitleExist(rule, value, callback) {
      queryOne({title: value}).then(response => {
        if (response.data.data) {
          callback(new Error('剧目已存在'))
        } else {
          callback()
        }
      })
    }
  },
  computed: {
    baseUrl() {
      return process.env.VUE_APP_IMG_SERVER
    }
  },
  watch: {
    dialogStatus: function (val) {
      //TODO:根据打开对话框的类型的不同,更改表单检验规则
      if (val === 'create') {
        this.rules.title = [
          {required: true, message: '标题不能为空', trigger: 'blur'},
          {validator: this.validateTitleExist, trigger: 'blur'}
        ]
      } else if (val === 'update') {
        this.rules.title = [
          {required: true, message: '标题不能为空', trigger: 'blur'}
        ]
      }
    }
  }
}
</script>
<style scoped>
.cover-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cover-uploader >>> .el-upload:hover {
  border-color: #409EFF;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 180px;
  line-height: 180px;
  text-align: center;
}

>>> .el-image.cover {
  width: 150px;
  height: auto;
  display: block;
}
</style>
